<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="订单编号" prop="orderNumber">
              <el-input v-model="queryParams.orderNumber" placeholder="请输入订单编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="下单时间" prop="orderTime">
              <el-date-picker
                v-model="dateRange"
                value-format="YYYY-MM-DD"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                clearable
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Close" @click="handleClose">关闭</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="spuOrderList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" v-if="false"/>
        <el-table-column label="订单ID" align="center" prop="orderId" v-if="false" />
        <el-table-column label="订单编号" align="center" prop="orderNumber" />
        <el-table-column label="订单状态">
          <template #default="scope">
            <el-tag type="warning" v-if="scope.row.orderStatus === 'Pending'">待支付</el-tag>
            <el-tag type="primary" v-else-if="scope.row.orderStatus === 'Paid'">已付款</el-tag>
            <el-tag type="primary" v-else-if="scope.row.orderStatus === 'Processing'">处理中</el-tag>
            <el-tag type="success" v-else-if="scope.row.orderStatus === 'Completed'">已完成</el-tag>
            <el-tag type="danger" v-else-if="scope.row.orderStatus === 'Cancelled'">已取消</el-tag>
            <el-tag type="danger" v-else-if="scope.row.orderStatus === 'Refunded'">已退款</el-tag>
            <el-tag v-else>未定义状态</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="服务名称" align="center" prop="serviceType" />
        <el-table-column label="姓名" align="center" prop="userName" />
        <el-table-column label="联系电话" align="center" prop="contactPhone" />
        <el-table-column label="邮箱" align="center" prop="email" />
        <el-table-column label="下单时间" align="center" prop="orderTime" width="180">
        </el-table-column>
        <el-table-column label="订单金额" align="center" prop="amount">
          <template #default="scope">
            <el-text>{{ scope.row.amount / 100 }} 元</el-text>
          </template>
        </el-table-column>
<!--        <el-table-column label="支付金额" align="center" prop="paymentAmount" />-->
        <el-table-column label="支付时间" align="center" prop="paymentTime" width="180">
        </el-table-column>
        <el-table-column label="完成时间" align="center" prop="completionTime" width="180">
        </el-table-column>
        <el-table-column label="评价状态" align="center" prop="review">
          <template #default="scope">
              <el-text v-if="scope.row.review == '1'">已评价</el-text>
              <el-text v-else>待评价</el-text>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="orderRemark" />
<!--        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
<!--          <template #default="scope">-->
<!--            <el-tooltip content="修改" placement="top">-->
<!--              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['lawyer:spuOrder:edit']"></el-button>-->
<!--            </el-tooltip>-->
<!--            <el-tooltip content="删除" placement="top">-->
<!--              <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['lawyer:spuOrder:remove']"></el-button>-->
<!--            </el-tooltip>-->
<!--          </template>-->
<!--        </el-table-column>-->
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改订单信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="spuOrderFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单编号" prop="orderNumber">
          <el-input v-model="form.orderNumber" placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="下单用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入下单用户ID" />
        </el-form-item>
        <el-form-item label="下单用户姓名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入下单用户姓名" />
        </el-form-item>
        <el-form-item label="下单时间" prop="orderTime">
          <el-date-picker clearable
                          v-model="form.orderTime"
                          type="datetime"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          placeholder="请选择下单时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="订单金额" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入订单金额" />
        </el-form-item>
        <el-form-item label="支付方式 (Alipay支付宝，WeChatPay微信, CreditCard信用卡, DebitCard借记卡，BankTransfer银行转帐)" prop="paymentMethod">
          <el-input v-model="form.paymentMethod" placeholder="请输入支付方式 (Alipay支付宝，WeChatPay微信, CreditCard信用卡, DebitCard借记卡，BankTransfer银行转帐)" />
        </el-form-item>
        <el-form-item label="支付金额" prop="paymentAmount">
          <el-input v-model="form.paymentAmount" placeholder="请输入支付金额" />
        </el-form-item>
        <el-form-item label="支付时间" prop="paymentTime">
          <el-date-picker clearable
                          v-model="form.paymentTime"
                          type="datetime"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          placeholder="请选择支付时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="完成时间" prop="completionTime">
          <el-date-picker clearable
                          v-model="form.completionTime"
                          type="datetime"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          placeholder="请选择完成时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="交易ID" prop="transactionId">
          <el-input v-model="form.transactionId" placeholder="请输入交易ID" />
        </el-form-item>
        <el-form-item label="评价状态(0待评价，已评价）" prop="review">
          <el-input v-model="form.review" placeholder="请输入评价状态(0待评价，已评价）" />
        </el-form-item>
        <el-form-item label="备注" prop="orderRemark">
          <el-input v-model="form.orderRemark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="是否已经支付 (0 未支付，1已支付）" prop="payed">
          <el-input v-model="form.payed" placeholder="请输入是否已经支付 (0 未支付，1已支付）" />
        </el-form-item>
        <el-form-item label="取消时间" prop="cancellationTime">
          <el-date-picker clearable
                          v-model="form.cancellationTime"
                          type="datetime"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          placeholder="请选择取消时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="是否需要指派律师处理" prop="dispatchable">
          <el-input v-model="form.dispatchable" placeholder="请输入是否需要指派律师处理" />
        </el-form-item>
        <el-form-item label="接收文件邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入接收文件邮箱" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="WxUserOrder" lang="ts">
import { listSpuOrder, getSpuOrder } from '@/api/trade/order';
import { SpuOrderVo, SpuOrderForm, SpuOrderQuery } from '@/api/trade/order/types';
import { WxUserVo } from '@/api/wxuser/types';
import { getWxUser } from '@/api/wxuser';
import { RouteLocationNormalized } from 'vue-router';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const spuOrderList = ref<SpuOrderVo[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const queryFormRef = ref<ElFormInstance>();
const spuOrderFormRef = ref<ElFormInstance>();
const defaultWxUser = ref<WxUserVo>();
const route = useRoute();
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: SpuOrderForm = {
  orderId: undefined,
  orderNumber: undefined,
  orderStatus: undefined,
  serviceType: undefined,
  contactPhone: undefined,
  userId: undefined,
  userName: undefined,
  orderTime: undefined,
  amount: undefined,
  paymentMethod: undefined,
  paymentAmount: undefined,
  paymentTime: undefined,
  completionTime: undefined,
  transactionId: undefined,
  review: undefined,
  orderRemark: undefined,
  payed: undefined,
  cancellationTime: undefined,
  closeType: undefined,
  dispatchable: undefined,
  email: undefined
}
const data = reactive<PageData<SpuOrderForm, SpuOrderQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderNumber: undefined,
    orderStatus: undefined,
    serviceType: undefined,
    contactPhone: undefined,
    userId: undefined,
    userName: undefined,
    orderTime: undefined,
    amount: undefined,
    paymentMethod: undefined,
    paymentAmount: undefined,
    paymentTime: undefined,
    completionTime: undefined,
    transactionId: undefined,
    review: undefined,
    orderRemark: undefined,
    payed: undefined,
    cancellationTime: undefined,
    closeType: undefined,
    dispatchable: undefined,
    email: undefined,
    params: {
    }
  },
  rules: {
    orderId: [
      { required: true, message: "订单ID不能为空", trigger: "blur" }
    ],
    orderNumber: [
      { required: true, message: "订单编号不能为空", trigger: "blur" }
    ],
    orderStatus: [
      { required: true, message: "订单状态(Pending=待处理，Paid=已付款，Processing=处理中，Completed=已完成，Cancelled=已取消，Refunded=已退款）不能为空", trigger: "change" }
    ],
    serviceType: [
      { required: true, message: "服务类型不能为空", trigger: "change" }
    ],
    contactPhone: [
      { required: true, message: "联系电话不能为空", trigger: "blur" }
    ],
    userId: [
      { required: true, message: "下单用户ID不能为空", trigger: "blur" }
    ],
    userName: [
      { required: true, message: "下单用户姓名不能为空", trigger: "blur" }
    ],
    orderTime: [
      { required: true, message: "下单时间不能为空", trigger: "blur" }
    ],
    amount: [
      { required: true, message: "订单金额不能为空", trigger: "blur" }
    ],
    paymentMethod: [
      { required: true, message: "支付方式 (Alipay支付宝，WeChatPay微信, CreditCard信用卡, DebitCard借记卡，BankTransfer银行转帐)不能为空", trigger: "blur" }
    ],
    paymentAmount: [
      { required: true, message: "支付金额不能为空", trigger: "blur" }
    ],
    paymentTime: [
      { required: true, message: "支付时间不能为空", trigger: "blur" }
    ],
    completionTime: [
      { required: true, message: "完成时间不能为空", trigger: "blur" }
    ],
    transactionId: [
      { required: true, message: "交易ID不能为空", trigger: "blur" }
    ],
    review: [
      { required: true, message: "评价状态(0待评价，已评价）不能为空", trigger: "blur" }
    ],
    orderRemark: [
      { required: true, message: "备注不能为空", trigger: "blur" }
    ],
    payed: [
      { required: true, message: "是否已经支付 (0 未支付，1已支付）不能为空", trigger: "blur" }
    ],
    cancellationTime: [
      { required: true, message: "取消时间不能为空", trigger: "blur" }
    ],
    closeType: [
      { required: true, message: "订单关闭原因1-超时未支付 2-买家取消不能为空", trigger: "change" }
    ],
    dispatchable: [
      { required: true, message: "是否需要指派律师处理不能为空", trigger: "blur" }
    ],
    email: [
      { required: true, message: "接收文件邮箱不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询订单信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listSpuOrder(proxy?.addDateRange(queryParams.value, dateRange.value));
  spuOrderList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  spuOrderFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: SpuOrderVo[]) => {
  ids.value = selection.map(item => item.orderId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加订单信息';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: SpuOrderVo) => {
  reset();
  const _orderId = row?.orderId || ids.value[0];
  const res = await getSpuOrder(_orderId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改订单信息';
}

/** 提交按钮 */
const submitForm = () => {
  spuOrderFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.orderId) {
        await updateSpuOrder(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addSpuOrder(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: SpuOrderVo) => {
  const _orderIds = row?.orderId || ids.value;
  await proxy?.$modal.confirm('是否确认删除当前选中的数据项？').finally(() => loading.value = false);
  await delSpuOrder(_orderIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

const handleClose = () => {
  const obj: RouteLocationNormalized = {
    fullPath: '',
    hash: '',
    matched: [],
    meta: undefined,
    name: undefined,
    params: undefined,
    query: undefined,
    redirectedFrom: undefined,
    path: '/wxuser/WxUser'
  };
  proxy?.$tab.closeOpenPage(obj);
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('lawyer/spuOrder/export', {
    ...queryParams.value
  }, `SpuOrder_${new Date().getTime()}.xlsx`)
};

const loadWxUser = async (wxUserId: string | number) => {
  const res = await getWxUser(wxUserId);
  defaultWxUser.value = res.data;
  queryParams.value.userId = wxUserId;
  await getList();
};

onMounted(() => {
  loadWxUser(route.params && (route.params.wxUserId as string));
});
</script>
